import tkinter as tk
from tkinter import ttk, messagebox
import random
import json
import os
from datetime import datetime, timedelta
from poem_content_manager import PoemContentManager

class UserManager:
    def __init__(self):
        self.users_file = "users.json"
        self.users_data = self.load_users()
        
    def load_users(self):
        if os.path.exists(self.users_file):
            with open(self.users_file, "r", encoding="utf-8") as f:
                return json.load(f)
        return {"users": [], "current_user": None}
    
    def save_users(self):
        with open(self.users_file, "w", encoding="utf-8") as f:
            json.dump(self.users_data, f, ensure_ascii=False, indent=4)
    
    def get_current_user(self):
        return self.users_data["current_user"]
    
    def set_current_user(self, user_id):
        self.users_data["current_user"] = user_id
        self.save_users()
    
    def get_user_history_file(self, user_id):
        for user in self.users_data["users"]:
            if user["id"] == user_id:
                return user["history_file"]
        return None

class PoemReciteApp:
    def __init__(self, root):
        self.root = root
        self.root.title('小学生必背古诗词75+80首背诵小助手')
        self.root.geometry('1000x600')  # 增加窗口宽度以适应左右分栏布局
        
        # 初始化用户管理器
        self.user_manager = UserManager()
        
        # 初始化诗词内容管理器
        self.poem_content_manager = PoemContentManager()
        
        # 导入诗词列表
        from poem_recite import poems, load_history, save_history, get_review_schedule
        self.poems = poems
        self.get_review_schedule = get_review_schedule
        
        # 自定义历史记录加载和保存函数
        self.load_history = self.load_user_history
        self.save_history = self.save_user_history
        
        self.history = {}
        self.to_recite = []
        self.recite_record = []
        self.current_poem = None
        self.current_idx = 0
        self.show_content = False  # 是否显示原文
        self.current_poem_content = ""  # 当前诗词内容
        
        self.setup_user_selection()
        
    def setup_user_selection(self):
        self.user_frame = ttk.Frame(self.root, padding='10')
        self.user_frame.pack(fill='x')
        
        ttk.Label(self.user_frame, text='请选择用户：').pack(side='left')
        self.user_var = tk.StringVar()
        self.user_combo = ttk.Combobox(self.user_frame, textvariable=self.user_var, state='readonly')
        self.user_combo['values'] = [user['name'] for user in self.user_manager.users_data['users']]
        
        # 设置默认选择的用户
        if self.user_combo['values']:
            self.user_combo.set(self.user_combo['values'][0])
            
        self.user_combo.pack(side='left', padx=5)
        
        ttk.Button(self.user_frame, text='确认选择', command=self.on_user_selected).pack(side='left', padx=5)
    
    def on_user_selected(self):
        selected_name = self.user_var.get()
        if not selected_name:
            messagebox.showwarning('提示', '请选择一个用户！')
            return
        
        # 设置默认选择
        if not self.user_combo.get():
            self.user_combo.set(self.user_combo['values'][0] if self.user_combo['values'] else '')
            if not self.user_combo.get():
                messagebox.showwarning('提示', '没有可用的用户！')
                return
        
        for user in self.user_manager.users_data['users']:
            if user['name'] == selected_name:
                self.user_manager.set_current_user(user['id'])
                self.history = self.load_history()
                self.user_frame.pack_forget()
                self.setup_ui()
                break
    
    def setup_ui(self):
        # 主菜单区域
        self.menu_frame = ttk.Frame(self.root, padding='10')
        self.menu_frame.pack(fill='x')
        
        ttk.Label(self.menu_frame, text='请输入要抽查的最大页码：').pack(side='left')
        self.max_num_var = tk.StringVar(value='20')
        self.max_num_entry = ttk.Entry(self.menu_frame, textvariable=self.max_num_var, width=10)
        self.max_num_entry.pack(side='left', padx=5)
        
        ttk.Button(self.menu_frame, text='开始背诵', command=self.start_recite).pack(side='left', padx=5)
        ttk.Button(self.menu_frame, text='重置记录', command=self.reset_history).pack(side='left', padx=5)
        ttk.Button(self.menu_frame, text='更新诗词内容', command=self.update_poem_contents).pack(side='left', padx=5)
        
        # 诗词显示区域 - 使用左右分栏布局
        self.poem_frame = ttk.Frame(self.root, padding='10')
        self.poem_frame.pack(fill='both', expand=True)
        
        # 创建左右分栏
        self.left_frame = ttk.Frame(self.poem_frame)
        self.left_frame.pack(side='left', fill='both', expand=True, padx=(0, 10))
        
        self.right_frame = ttk.Frame(self.poem_frame, relief='ridge', borderwidth=1)
        self.right_frame.pack(side='right', fill='y', padx=(10, 0))
        # 设置右侧框架的最小宽度
        self.right_frame.pack_propagate(False)
        self.right_frame.config(width=350, height=450)  # 调整宽度以更好地显示诗词
        
        # 左侧：诗词信息和操作区域
        self.poem_info = ttk.Label(self.left_frame, text='点击"开始背诵"开始...', font=('宋体', 14))
        self.poem_info.pack(pady=20)
        
        self.stats_info = ttk.Label(self.left_frame, text='')
        self.stats_info.pack(pady=10)
        
        # 原文控制按钮放在左侧
        self.content_control_frame = ttk.Frame(self.left_frame)
        self.content_control_frame.pack(pady=10)
        
        self.show_content_btn = ttk.Button(self.content_control_frame, text='显示原文', 
                                          command=self.toggle_content_display, state='disabled')
        self.show_content_btn.pack()
        
        # 评分区域（保持在左侧）
        self.score_frame = ttk.Frame(self.left_frame)
        self.score_frame.pack(pady=20)
        
        ttk.Label(self.score_frame, text='掌握程度：').pack(side='left')
        for i in range(1, 7):
            ttk.Button(self.score_frame, text=str(i), 
                      command=lambda x=i: self.rate_mastery(x)).pack(side='left', padx=2)
        
        # 下一首按钮（保持在左侧）
        self.next_btn = ttk.Button(self.left_frame, text='下一首', 
                                  command=self.next_poem, state='disabled')
        self.next_btn.pack(pady=10)
        
        # 右侧：原文显示区域
        self.content_label = ttk.Label(self.right_frame, text='诗词原文', font=('宋体', 12, 'bold'))
        self.content_label.pack(pady=(0, 10))
        
        self.content_text = tk.Text(self.right_frame, width=40, height=20, wrap='word', 
                                   font=('宋体', 14), state='disabled',
                                   bg='#f8f8f8', relief='ridge', bd=1,
                                   spacing1=5, spacing2=8, spacing3=5)
        self.content_text.pack(fill='both', expand=True, padx=5, pady=5)
        
        # 配置居中对齐的标签
        self.content_text.tag_configure('center', justify='center')
        
        # 初始化右侧内容
        self.content_text.config(state='normal')
        self.content_text.insert('1.0', '开始背诵后，诗词原文将显示在这里', 'center')
        self.content_text.config(state='disabled')
        
        # 统计信息
        self.summary_text = tk.Text(self.root, height=5, wrap='word', state='disabled')
        self.summary_text.pack(fill='x', padx=10, pady=5)
    
    def start_recite(self):
        try:
            max_num = int(self.max_num_var.get())
            if max_num <= 0:
                raise ValueError
        except ValueError:
            messagebox.showerror('错误', '请输入有效的数字！')
            return
        
        # 生成待背诵列表
        selected_poems = [(num, name) for num, name in self.poems if num < max_num]
        if not selected_poems:
            messagebox.showinfo('提示', '没有找到小于该序号的诗词。')
            return
        
        self.to_recite = []
        for num, name in selected_poems:
            poem_key = f"{num}-{name}"
            poem_history = self.history.get(poem_key, {'count': 0, 'mastery_level': 1, 'last_review': None})
            if not isinstance(poem_history, dict):
                poem_history = {'count': poem_history, 'mastery_level': 1, 'last_review': None}
            
            if self.get_review_schedule(poem_history.get('last_review'), poem_history.get('mastery_level', 1)):
                self.to_recite.append((num, name))
        
        if not self.to_recite:
            messagebox.showinfo('提示', '当前没有需要复习的诗词。')
            return
        
        random.shuffle(self.to_recite)
        self.recite_record = []
        self.current_idx = 0
        self.show_next_poem()
    
    def show_next_poem(self):
        if self.to_recite:
            num, name = self.to_recite[0]
            self.current_poem = (num, name)
            poem_key = f"{num}-{name}"
            poem_history = self.history.get(poem_key, {'count': 0, 'mastery_level': 1, 'last_review': None})
            if not isinstance(poem_history, dict):
                poem_history = {'count': poem_history, 'mastery_level': 1, 'last_review': None}
            
            self.poem_info.config(text=f"第{self.current_idx + 1}首：{name}（序号：{num}）")
            self.stats_info.config(
                text=f"已背诵次数：{poem_history['count']}次，"
                     f"掌握程度：{poem_history.get('mastery_level', 1)}/6")
            
            # 获取诗词内容
            self.current_poem_content = self.poem_content_manager.get_poem_content(name)
            if self.current_poem_content:
                self.show_content_btn.config(state='normal')
            else:
                self.show_content_btn.config(state='disabled')
            
            # 重置显示状态
            self.show_content = False
            self.show_content_btn.config(text='显示原文')
            
            # 更新右侧内容区域
            self.content_text.config(state='normal')
            self.content_text.delete('1.0', 'end')
            if self.current_poem_content:
                self.content_text.insert('1.0', '点击"显示原文"按钮查看诗词内容', 'center')
            else:
                self.content_text.insert('1.0', '当前诗词暂无原文内容', 'center')
            self.content_text.config(state='disabled')
            
            self.next_btn.config(state='disabled')
        else:
            self.show_summary()
    
    def rate_mastery(self, score):
        if self.current_poem:
            num, name = self.current_poem
            poem_key = f"{num}-{name}"
            poem_history = self.history.get(poem_key, {'count': 0, 'mastery_level': 1, 'last_review': None})
            if not isinstance(poem_history, dict):
                poem_history = {'count': poem_history, 'mastery_level': 1, 'last_review': None}
            
            self.history[poem_key] = {
                'count': poem_history['count'] + 1,
                'mastery_level': score,
                'last_review': datetime.now()
            }
            
            self.recite_record.append((num, name))
            
            # 如果评分是5或6分，显示鼓励效果
            if score >= 5:
                self.show_encouragement(score, name)
            
            self.next_btn.config(state='normal')
    
    def show_encouragement(self, score, poem_name):
        """显示鼓励效果"""
        import random
        
        # 不同分数的鼓励文案
        if score == 6:
            titles = ['🎉 完美掌握！', '🎆 太棒了！', '⭐ 诗词大师！', '🏆 精彩绝伦！']
            messages = [
                f'恭喜您完美掌握了《{poem_name}》！\n您的背诵水平非常出色！',
                f'太棒了！《{poem_name}》您已经掌握得很熟练！\n继续加油，您就是诗词大师！',
                f'精彩！《{poem_name}》背诵得无懈可击！\n您的古诗文底越来越深厚了！',
                f'了不起！《{poem_name}》已经被您完全征服！\n这样的水平可以挑战更难的诗词了！'
            ]
            colors = ['#FFD700', '#FF6B6B', '#4ECDC4', '#45B7D1']  # 金色、红色、蓝绿色、蓝色
        else:  # score == 5
            titles = ['😄 做得很好！', '👍 掌握得不错！', '🌟 进步明显！', '💪 越来越棒！']
            messages = [
                f'很好！《{poem_name}》您已经掌握得相当不错！\n再加把力就能达到完美水平！',
                f'做得好！《{poem_name}》的背诵水平很高！\n您的努力正在获得回报！',
                f'进步很明显！《{poem_name}》已经背得很流利！\n继续保持这个状态！',
                f'太棒了！《{poem_name}》的掌握程度越来越高！\n您的记忆力真不错！'
            ]
            colors = ['#98D8C8', '#F7DC6F', '#BB8FCE', '#85C1E9']  # 温和的绿色、黄色、紫色、蓝色
        
        # 随机选择一个鼓励文案
        title = random.choice(titles)
        message = random.choice(messages)
        bg_color = random.choice(colors)
        
        # 创建鼓励弹窗
        encouragement_window = tk.Toplevel(self.root)
        encouragement_window.title(title)
        encouragement_window.geometry('400x200')
        encouragement_window.transient(self.root)
        encouragement_window.grab_set()
        encouragement_window.configure(bg=bg_color)
        
        # 设置窗口居中
        encouragement_window.geometry('+{}+{}'.format(
            self.root.winfo_rootx() + 300,
            self.root.winfo_rooty() + 200
        ))
        
        # 标题标签
        title_label = tk.Label(encouragement_window, text=title, 
                              font=('宋体', 16, 'bold'), 
                              bg=bg_color, fg='white')
        title_label.pack(pady=20)
        
        # 消息标签
        message_label = tk.Label(encouragement_window, text=message, 
                                font=('宋体', 12), 
                                bg=bg_color, fg='white', 
                                wraplength=350, justify='center')
        message_label.pack(pady=10)
        
        # 确认按钮
        ok_button = tk.Button(encouragement_window, text='继续加油！', 
                             font=('宋体', 12, 'bold'),
                             command=encouragement_window.destroy,
                             bg='white', fg=bg_color,
                             relief='raised', bd=2)
        ok_button.pack(pady=15)
        
        # 同时在右侧文本区域显示鼓励信息（如果存在的话）
        if hasattr(self, 'content_text') and self.content_text:
            self.content_text.config(state='normal')
            current_content = self.content_text.get('1.0', 'end').strip()
            if current_content and '点击' not in current_content:
                # 如果当前显示的是诗词内容，在下方添加鼓励信息
                self.content_text.insert('end', '\n\n' + '⭐' * 10 + '\n', 'center')
                self.content_text.insert('end', title + '\n', 'center')
                self.content_text.insert('end', '⭐' * 10, 'center')
            self.content_text.config(state='disabled')
        
        # 2秒后自动关闭弹窗
        encouragement_window.after(3000, encouragement_window.destroy)
    
    def next_poem(self):
        if self.to_recite:
            self.to_recite.pop(0)
            self.current_idx += 1
            self.show_next_poem()
    
    def show_summary(self):
        self.poem_info.config(text='背诵完成！')
        self.stats_info.config(text='')
        self.next_btn.config(state='disabled')
        
        # 更新右侧内容区域
        self.show_content_btn.config(state='disabled', text='显示原文')
        self.content_text.config(state='normal')
        self.content_text.delete('1.0', 'end')
        self.content_text.insert('1.0', '背诵完成！\n\n恭喜您完成了本次背诵练习。', 'center')
        self.content_text.config(state='disabled')
        self.show_content = False
        
        summary = "本次背诵记录：\n"
        for i, (num, name) in enumerate(self.recite_record, 1):
            poem_key = f"{num}-{name}"
            poem_data = self.history[poem_key]
            summary += f"{i}. 序号：{num}，名称：{name}，"
            summary += f"已背诵次数：{poem_data['count']}次，"
            summary += f"掌握程度：{poem_data['mastery_level']}/6\n"
        
        self.summary_text.config(state='normal')
        self.summary_text.delete('1.0', 'end')
        self.summary_text.insert('1.0', summary)
        self.summary_text.config(state='disabled')
        
        self.save_history(self.history)
    
    def load_user_history(self):
        current_user = self.user_manager.get_current_user()
        if not current_user:
            return {}
        
        history_file = self.user_manager.get_user_history_file(current_user)
        if not history_file:
            return {}
        
        if os.path.exists(history_file):
            with open(history_file, "r", encoding="utf-8") as f:
                history = json.load(f)
                for key in history:
                    if isinstance(history[key], dict) and 'last_review' in history[key]:
                        history[key]['last_review'] = datetime.fromisoformat(history[key]['last_review'])
                return history
        return {}
    
    def save_user_history(self, history):
        current_user = self.user_manager.get_current_user()
        if not current_user:
            return
        
        history_file = self.user_manager.get_user_history_file(current_user)
        if not history_file:
            return
        
        history_copy = {}
        for key, value in history.items():
            if isinstance(value, dict) and 'last_review' in value:
                history_copy[key] = value.copy()
                history_copy[key]['last_review'] = value['last_review'].isoformat()
            else:
                history_copy[key] = value
        
        with open(history_file, "w", encoding="utf-8") as f:
            json.dump(history_copy, f, ensure_ascii=False, indent=4)
    
    def reset_history(self):
        current_user = self.user_manager.get_current_user()
        if not current_user:
            return
        
        if messagebox.askyesno('确认', '是否要重置当前用户的背诵记录？（将会备份原有记录）'):
            history_file = self.user_manager.get_user_history_file(current_user)
            if os.path.exists(history_file):
                backup_file = f"{history_file[:-5]}_backup_{datetime.now().strftime('%Y%m%d_%H%M%S')}.json"
                os.rename(history_file, backup_file)
                self.history = {}
                self.save_history(self.history)
                messagebox.showinfo('提示', '背诵记录已重置。')
            else:
                messagebox.showinfo('提示', '没有找到背诵记录文件。')
    
    def toggle_content_display(self):
        """切换原文显示/隐藏"""
        if not self.current_poem_content:
            messagebox.showinfo('提示', '当前诗词没有原文内容。')
            return
        
        if self.show_content:
            # 隐藏原文
            self.content_text.config(state='normal')
            self.content_text.delete('1.0', 'end')
            self.content_text.insert('1.0', '点击"显示原文"按钮查看诗词内容', 'center')
            self.content_text.config(state='disabled')
            self.show_content_btn.config(text='显示原文')
            self.show_content = False
        else:
            # 显示原文
            self.content_text.config(state='normal')
            self.content_text.delete('1.0', 'end')
            self.content_text.insert('1.0', self.current_poem_content, 'center')
            self.content_text.config(state='disabled')
            self.show_content_btn.config(text='隐藏原文')
            self.show_content = True
    
    def update_poem_contents(self):
        """批量更新诗词内容"""
        if messagebox.askyesno('确认', '是否要批量更新诗词内容？这可能需要一些时间。'):
            try:
                # 获取当前选择的诗词范围
                max_num = int(self.max_num_var.get()) if self.max_num_var.get() else 200
                selected_poems = [(num, name) for num, name in self.poems if num < max_num]
                
                # 使用进度条显示更新进度
                progress_window = tk.Toplevel(self.root)
                progress_window.title('更新诗词内容')
                progress_window.geometry('400x150')
                progress_window.transient(self.root)
                progress_window.grab_set()
                
                progress_label = ttk.Label(progress_window, text='正在更新诗词内容...')
                progress_label.pack(pady=20)
                
                progress_bar = ttk.Progressbar(progress_window, length=300, mode='determinate')
                progress_bar.pack(pady=10)
                progress_bar['maximum'] = len(selected_poems)
                
                status_label = ttk.Label(progress_window, text='')
                status_label.pack(pady=10)
                
                def update_progress():
                    success_count = 0
                    for i, (num, name) in enumerate(selected_poems):
                        # 更新进度
                        progress_bar['value'] = i + 1
                        status_label.config(text=f'正在处理: {name}')
                        progress_window.update()
                        
                        # 获取诗词内容
                        content = self.poem_content_manager.get_poem_content(name)
                        if content:
                            success_count += 1
                    
                    # 完成
                    status_label.config(text=f'更新完成！成功: {success_count}/{len(selected_poems)}')
                    
                    # 2秒后关闭窗口
                    progress_window.after(2000, progress_window.destroy)
                
                # 在主线程中执行更新
                progress_window.after(100, update_progress)
                
            except ValueError:
                messagebox.showerror('错误', '请输入有效的数字！')
            except Exception as e:
                messagebox.showerror('错误', f'更新失败：{str(e)}')

if __name__ == '__main__':
    root = tk.Tk()
    app = PoemReciteApp(root)
    root.mainloop()